import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

let REQUEST_URL // 用于在网络请求错误时显示


// const API_PREFIX = process.env.VUE_APP_API_PREFIX

const config = {
  baseURL: process.env.NODE_ENV === 'development' ? '/api' : '',
  withCredentials: true,
  crossDomain: true
}

const _axios = axios.create(config)

// 请求拦截器
_axios.interceptors.request.use(config => {
  config.showLoading && store.commit('show_loading')
  const { token } = store.getters.userInfo
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
_axios.interceptors.response.use(response => {
  const requestConfig = response.config
  const url = requestConfig.url
  store.commit('hide_loading')
  // 处理 下载响应
  if (requestConfig.responseType === 'blob') {
    // 正确处理
    if (response.headers && response.headers['content-disposition']) {
      // 获取文件名
      let filename; const contentDisposition = response.headers && response.headers['content-disposition']

      if (contentDisposition.includes('fileName')) {
        const contentDispositionArr = contentDisposition.split(';')
        contentDispositionArr.some(arrOne => {
          if (arrOne.includes('fileName')) {
            filename = decodeURIComponent((arrOne.split('=', 2)[1] + ''))
            return true
          }
        })
      }
      filename = filename || '文件'
      handleDownload(response.data, filename)
      return Promise.resolve({
        code: null,
        data: response.data
      })
      // 错误处理
    } else {
      // 读取Blob对象内容
      (new window.Response(response.data)).text().then(res => {
        res = JSON.parse(res) // 解析
        Message.closeAll()
        Message.error(`${url}-接口错误-${res.msg}`)
        console.log(`Error-${url}-download-${res.msg}`)
        return Promise.resolve(res)
      })
    }
    // 处理 其他响应
  } else {
    // token失效 登出操作
    if (response.data && +response.data.code === 1002) {
      store.dispatch('user/loginOut')
      console.log('this.$router', require('@/router').default)
      const router = require('@/router').default
      router.replace({
        path: '/login'
      })
      // store.dispatch('tagsView/delAllVisitedViews')
      // return Promise.reject('登录失效')
    }
    // console.log('response', response.data)
    const res = (response && response.data) || {}
    if (process.env.VUE_APP_CONSOLE) {
      console.log(`---------${url}---------res:`, res)
    }
    if (+res.code !== 200 && res.msg !== '操作成功') {
      Message.closeAll()
      Message.error(res.msg)
      console.log(`接口：${url}-错误-res:${res}`)
      return Promise.reject(res.msg)
    }
    return Promise.resolve(res.data || {})
  }
}, err => { // 处理错误
  store.commit('hide_loading')
  if (err && process.env.VUE_APP_CONSOLE) {
    console.log(`api：${REQUEST_URL}，ERROR: ` + err)
  }
  Message.closeAll()
  Message.error(`${err.message || '网络错误'}`)
  return Promise.reject(err.message || '网络错误')
})

export const request = function ({ url, showLoading = true, ...rest } = {}) {
  showLoading && store.commit('show_loading')
  REQUEST_URL = url
  return _axios.request({
    url,
    ...rest,
    showLoading
  })
}

export const get = function (url, params = {}, options = {}) {
  return request({
    method: 'GET',
    url,
    params,
    ...options
  })
}

export const post = async function (url, data, options = {}) {
  data = {
    ...data
  }
  return request({
    method: 'POST',
    url,
    data,
    ...options
  })
}

export const put = function (url, data, options = {}) {
  return request({
    method: 'PUT',
    url,
    data,
    ...options
  })
}

export const del = function (url, data, options = {}) {
  return request({
    method: 'DELETE',
    url,
    data,
    ...options
  })
}

export const download = function (url, data) {
  return post(url, data, {
    headers: {
      'Content-Type': 'application/json;application/octet-stream'
    },
    responseType: 'blob'
  })
}

export const downloadGet = function (url, data) {
  return get(url, data, {
    headers: {
      'Content-Type': 'application/json;application/octet-stream'
    },
    responseType: 'blob'
  })
}

const handleDownload = function (data, filename) { // 文件下载需后端提供下载接口
  if (!data) return
  const { saveAs } = require('file-saver')
  saveAs(new Blob([data], {
    type: 'application/octet-stream;'
  }), filename)
}

export class HTTP {
  request = request
  get = get
  post = post
  download = download
  downloadGet = downloadGet
  $message = Message
  put = put
  del = del
}

export default (Vue) => {
  Vue.prototype.$request = request
  Vue.prototype.$get = get
  Vue.prototype.$post = post
  Vue.prototype.$download = download
}
